# -*- coding: utf-8 -*-
from typing import List, Any

import yaml
from logger_setup import get_logger

yaml_tool_logger = get_logger('yaml_tool')
yamlFile = "config.yaml"

def get_dict():
    '''
    读取数据
    '''
    try:
        with open(yamlFile, 'r', encoding='utf-8') as f:
            d = yaml.load(f.read(), Loader=yaml.FullLoader)
            yaml_tool_logger.info(f'读取{yamlFile}成功')
        return d
    except Exception as e:
        yaml_tool_logger.warning(f'读取{yamlFile}失败')
        yaml_tool_logger.error(e)


def repair_data(nested_keys: List[str], data: Any):
    '''
    更新多层嵌套数据

    Args:
        nested_keys: 嵌套键的列表，如 ['level1', 'level2', 'target_key']
        data: 要更新的数据
    '''
    try:
        # 读取现有数据
        with open(yamlFile, 'r', encoding='utf-8') as f:
            dict_temp = yaml.safe_load(f) or {}

        # 递归更新嵌套字典
        current = dict_temp
        for key in nested_keys[:-1]:  # 遍历除最后一个键外的所有键
            if key not in current or not isinstance(current[key], dict):
                current[key] = {}  # 如果路径不存在，创建嵌套字典
            current = current[key]

        # 设置最终键的值
        current[nested_keys[-1]] = data

        # 写回文件
        with open(yamlFile, 'w', encoding='utf-8') as f:
            yaml.dump(dict_temp, f, allow_unicode=True, sort_keys=False)

        yaml_tool_logger.info(f'数据 {nested_keys} 更新成功')

    except Exception as e:
        yaml_tool_logger.warning(f'数据更新失败: {e}')
        yaml_tool_logger.error(e)
